package com.hhit.yb.compose_demo.views

import android.annotation.SuppressLint
import android.widget.Toast
import android.window.OnBackAnimationCallback
import androidx.activity.OnBackPressedCallback
import androidx.activity.OnBackPressedDispatcher
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.add
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PageSize
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.hhit.yb.compose_demo.models.SectionModel
import com.hhit.yb.compose_demo.viewModel.MainViewModel
import com.hhit.yb.compose_demo.viewModel.suggestionList
import com.hhit.yb.compose_demo.views.search.SearchBar
import com.hhit.yb.compose_demo.views.search.SearchDisplay
import com.hhit.yb.compose_demo.views.search.rememberSearchState
import kotlinx.coroutines.launch

internal val tabList = listOf("Components", "Layout", "State", "Gesture", "Graphics", "Theming")

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun HomeScreen(
    modifier: Modifier = Modifier,
    viewModel: MainViewModel,
    navigateToTutorial: (String) -> Unit,
) {
    Column(modifier = modifier.fillMaxSize()) {
        val context = LocalContext.current
        val state = rememberSearchState(
            initialResults = viewModel.sectionList,
            suggestions = suggestionList,
            timeoutMillis = 600
        ) { query: TextFieldValue ->
            viewModel.getSections(query.text)
        }

        val focusManager = LocalFocusManager.current
        val keyboardController = LocalSoftwareKeyboardController.current

//        val dispatcher:OnBackPressedDispatcher = LocalContext.current.getSystemService(OnBackPressedDispatcher::class.java)
        val dispatcher: OnBackPressedDispatcher =
            LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher

        val backCallback = remember {
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    if (!state.focused) {
                        isEnabled = false
                        Toast.makeText(context, "Back", Toast.LENGTH_SHORT).show()
                        dispatcher.onBackPressed()
                    } else {
                        state.query = TextFieldValue("")
                        state.focused = false
                        focusManager.clearFocus()
                        keyboardController?.hide()
                    }
                }
            }
        }

        DisposableEffect(dispatcher) { // dispose/relaunch if dispatcher changes
            dispatcher.addCallback(backCallback)
            onDispose {
                backCallback.remove() // avoid leaks!
            }
        }

        SearchBar(
            query = state.query,
            onQueryChange = { state.query = it },
            onSearchFocusChange = { state.focused = it },
            onClearQuery = { state.query = TextFieldValue("") },
            onBack = { state.query = TextFieldValue("") },
            searching = state.searching,
            focused = state.focused,
            modifier = modifier
        )

        when (state.searchDisplay) {
            // This is initial state, first time screen is opened or no query is done
            SearchDisplay.InitialResults -> {
                HomeContent(Modifier, state.initialResults, navigateToTutorial)
            }

            SearchDisplay.NoResults -> {
                Box(
                    modifier = Modifier
                        .padding(top = 16.dp)
                        .fillMaxWidth(),
                    contentAlignment = Alignment.Center
                ) {
                    Text("❌ No Results!", fontSize = 24.sp, color = Color(0xffDD2C00))
                }
            }

            SearchDisplay.Suggestions -> {
//                SuggestionGridLayout(suggestions = state.suggestions) {
//                    var text = state.query.text
//                    if (text.isEmpty()) text = it else text += " $it"
//                    text.trim()
//                    // Set text and cursor position to end of text
//                    state.query = TextFieldValue(text, TextRange(text.length))
//                }
            }

            SearchDisplay.Results -> {
//                TutorialListContent(modifier, state.searchResults, navigateToTutorial)
            }

            SearchDisplay.SearchInProgress -> {
                Box(
                    modifier = Modifier
                        .background(Color.White)
                        .fillMaxSize()
                )
            }
        }
    }
}


@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun HomeContent(
    modifier: Modifier,
    tutorialList: List<List<SectionModel>>,
    navigateToTutorial: (String) -> Unit
) {

    val pagerState: PagerState = rememberPagerState(
        initialPage = 0,
        initialPageOffsetFraction = 0f
    ) {
        // provide pageCount
        tabList.size
    }
    val coroutineScope = rememberCoroutineScope()

    ScrollableTabRow(
        modifier = modifier.fillMaxWidth(),
        containerColor = MaterialTheme.colorScheme.surface,
        contentColor = MaterialTheme.colorScheme.onSurface,
        edgePadding = 8.dp,
        selectedTabIndex = pagerState.currentPage,
    ) {
        tabList.forEachIndexed { index, title ->
            Tab(
                text = { Text(title) },
                selected = pagerState.currentPage == index,
                onClick = {
                    coroutineScope.launch {
                        pagerState.animateScrollToPage(index)
                    }
                },
            )
        }
    }

    HorizontalPager(
        modifier = Modifier.fillMaxSize(),
        pageSpacing = 0.dp,
        pageSize = PageSize.Fill,
        state = pagerState
    ) { page: Int ->
        when (page) {
            0 -> TutorialListContent(modifier, tutorialList[0], navigateToTutorial)
            1 -> TutorialListContent(modifier, tutorialList[1], navigateToTutorial)
            2 -> TutorialListContent(modifier, tutorialList[2], navigateToTutorial)
            3 -> TutorialListContent(modifier, tutorialList[3], navigateToTutorial)
            4 -> TutorialListContent(modifier, tutorialList[4], navigateToTutorial)
//            else -> ComingSoonScreen()
        }
    }
}


@SuppressLint("SuspiciousIndentation")
@Composable
fun TutorialListContent(
    modifier: Modifier = Modifier, tutorialList: List<SectionModel>,
    navigateToTutorial: (String) -> Unit
) {
    Surface(
        modifier = modifier.fillMaxSize(),
        color = Color(0xffEEEEEE)
    ) {
        val context = LocalContext.current
        Box {
            val scrollState = rememberLazyListState()

            LazyColumn(
                state = scrollState,
                contentPadding = WindowInsets.systemBars.only(WindowInsetsSides.Bottom)
                    .add(
                        WindowInsets(left = 8.dp, right = 8.dp, top = 16.dp, bottom = 16.dp)
                    )
                    .asPaddingValues(),
                verticalArrangement = Arrangement.spacedBy(8.dp),
                content = {
                    items(tutorialList.size) { index ->
                        var isExpanded by remember(key1 = tutorialList[index].title) {
                            mutableStateOf(
                                tutorialList[index].expanded
                            )
                        }
                        SectionCard(model = tutorialList[index], onClickAction = {
                            navigateToTutorial(it.title)
                        }, onExpandAction = {
                            tutorialList[index].expanded = !tutorialList[index].expanded
                            isExpanded = tutorialList[index].expanded
                              if (isExpanded) {
                                  Toast.makeText(context, "Expand", Toast.LENGTH_SHORT).show()
                              } else {
                                  Toast.makeText(context, "Collapse", Toast.LENGTH_SHORT).show()
                              }
                        }, expanded = isExpanded)
                    }
                })
        }
    }
}



















